package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    @ExceptionHandler
    public Result DuplicatedKeyExceptionHandler(SQLIntegrityConstraintViolationException ex){
        String s=ex.getMessage();
        log.error("异常信息：{}", s);
        if (s.contains("Duplicate entry")){
            String[] split = s.split(" ");
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }
        else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
    // 兜底异常处理
    @ExceptionHandler(Exception.class)
    public Result handleOtherException(Exception ex) {
        log.error("未知系统异常：", ex);
        return Result.error("系统异常，请联系管理员");
    }

}
